package com.qingzhuge.manager.autoconfigure;

import com.google.common.collect.Lists;
import com.qingzhuge.common.enums.ERoleType;
import com.qingzhuge.manager.entity.SysRole;
import com.qingzhuge.manager.entity.SysUser;
import com.qingzhuge.manager.service.ISysRoleService;
import com.qingzhuge.manager.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : zero.xiao
 * @description : 添加系统默认角色和用户
 * @date :2018/9/20 0020 下午 16:21
 * @modified :
 * @since : 1.0.0
 */
@Slf4j
@Order(3)
@Component
public class SysUserAndRoleRunner implements ApplicationRunner {
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysRoleService roleService;

    @Override
    public void run(ApplicationArguments args) {
        SysRole role = roleService.findByRoot();
        if (null == role) {
            role = saveRole();
        }
        SysUser user = userService.findByRoot();
        if (null == user) {
            saveUser(role);
        }else{
            log.debug("system root user:[{}]",user);
        }
    }

    private SysRole saveRole() {
        SysRole role = new SysRole();
        role.setRoot(true);
        role.setPermission("*");
        role.setName("超级角色");
        role.setType(ERoleType.SYSTEM);
        log.debug("=========Add system super roles=========");
        roleService.save(role);
        return role;
    }

    private void saveUser(SysRole role) {
        SysUser user = new SysUser();
        user.setName("超级管理员");
        user.setUsername("root");
        user.setRoot(true);
        user.setPassword("123456");
        List<SysRole> roleList = Lists.newArrayList();
        roleList.add(role);
        user.setRoles(roleList);
        try {
            userService.save(user);
            log.debug("=========Add system superuser=========: username:root | pwd: 123456");
        } catch (Exception e) {
            log.debug("=========system superuser=========: username:[{}]", user.getUsername());
        }
    }
}